<template>
    <el-container>
      <el-header>与您的宝贝聊天</el-header>
      <el-main>
        <div class="chat-container">
          <div v-for="msg in messages" :key="msg.id" :class="msg.isSelf ? 'message-bubble self' : 'message-bubble other'">
            {{ msg.content }}
          </div>
        </div>
        <div class="input-container">
          <el-input
            type="textarea"
            v-model="message"
            placeholder="在这里输入你的消息..."
            @keyup.enter="sendMessage">
          </el-input>
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </div>
      </el-main>
    </el-container>
  </template>
  
  <script>
  import axios from 'axios';
  import { v4 as uuidv4 } from 'uuid';
  
  export default {
    data() {
      return {
        message: '',
        messages: [],
        sessionId: uuidv4() // 在页面加载时生成一个唯一的sessionId
      };
    },
    methods: {
      sendMessage() {
        if (!this.message.trim()) {
          return; // 阻止发送空消息
        }
        const requestBody = {
          content: this.message,
          sessionId: this.sessionId // 包含sessionId
        };
        // 添加用户消息到消息列表
        this.messages.push({
          id: this.messages.length + 1,
          content: this.message,
          isSelf: true
        });
        this.message = ''; // 清空输入框
        axios.post('/api/chat/send', requestBody)
          .then(response => {
            const responseData = response.data;
            if (responseData && responseData.data && responseData.code === 0) {
              this.messages.push({
                id: this.messages.length + 1,
                content: responseData.data.content,
                isSelf: false
              });
            } else {
              console.error('接收到错误或格式无效:', responseData);
            }
          })
          .catch(error => {
            console.error('发送消息错误:', error);
            this.messages.push({
              id: this.messages.length + 1,
              content: `错误：${error.message || "与服务器通信失败"}`,
              isSelf: false
            });
          });
      }
    }
  }
  </script>
  
  <style scoped>
  .el-main {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  
  .chat-container {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #f9f9f9;
    display: flex;
    flex-direction: column;
  }
  
  .message-bubble {
    max-width: 70%;
    padding: 10px 15px;
    margin: 10px 0;
    border-radius: 20px;
    position: relative;
    word-wrap: break-word;
    white-space: pre-wrap;
  }
  
  .message-bubble.self {
    background: #d1eaff;
    align-self: flex-end;
    text-align: right;
  }
  
  .message-bubble.other {
    background: #f1f0f0;
    align-self: flex-start;
    text-align: left;
  }
  
  .input-container {
    display: flex;
    align-items: center;
    padding: 10px;
    background: #fff;
  }
  
  .el-input {
    flex: 1;
    margin-right: 10px;
  }
  </style>
  